package kt_test.network

import android.util.Log
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import kt_test.model.OxygenUploadRequest
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException

object OxygenUploader {

    private val client = OkHttpClient()
    private val JSON_MEDIA = "application/json".toMediaType()

    // Kotlin 调用方式，保留实例方法
    fun uploadData(
        request: OxygenUploadRequest,
        onSuccess: () -> Unit,
        onFailure: (String) -> Unit
    ) {
        val json = JSONObject().apply {
            put("userId", request.userId)
            put("gender", request.gender)
            put("age", request.age)

            val samplesArray = JSONArray()
            request.samples.forEach {
                val sampleObj = JSONObject().apply {
                    put("time", it.time)
                    put("spo2", it.spo2)
                }
                samplesArray.put(sampleObj)
            }

            put("samples", samplesArray)
        }

        val requestBody = json.toString().toRequestBody(JSON_MEDIA)

        val httpRequest = Request.Builder()
            .url("http://10.0.2.2:1514/vitalsign/uploadBatch") // 修改为你的服务器地址
            .post(requestBody)
            .build()

        client.newCall(httpRequest).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("OxygenUploader", "网络请求失败: ${e.message}", e)
                onFailure("网络请求失败: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    onSuccess()
                } else {
                    onFailure("服务器响应失败: ${response.code}")
                }
            }
        })
    }

    // 为 Java 兼容的静态方法，使用 Runnable 和 Consumer
    @JvmStatic
    fun uploadDataJava(
        data: OxygenUploadRequest,
        onSuccess: Runnable,
        onFailure: java.util.function.Consumer<String>
    ) {
        val json = JSONObject().apply {
            put("userId", data.userId)
            put("gender", data.gender)
            put("age", data.age)

            val samplesArray = JSONArray()
            data.samples.forEach {
                val sampleObj = JSONObject().apply {
                    put("time", it.time)
                    put("spo2", it.spo2)
                }
                samplesArray.put(sampleObj)
            }

            put("samples", samplesArray)
        }

        val requestBody = json.toString().toRequestBody(JSON_MEDIA)

        val httpRequest = Request.Builder()
            .url("http://10.0.2.2:1514/vitalsign/uploadBatch") // 修改为你的服务器地址
            .post(requestBody)
            .build()

        client.newCall(httpRequest).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("OxygenUploader", "网络请求失败: ${e.message}", e)
                onFailure.accept("网络请求失败: ${e.message}")
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    onSuccess.run()
                } else {
                    onFailure.accept("服务器响应失败: ${response.code}")
                }
            }
        })
    }
}
